//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.qst.crop.service.impl;

import com.qst.crop.dao.AddressDao;
import com.qst.crop.entity.Address;
import com.qst.crop.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDao addressDao;

    public AddressServiceImpl() {
    }

    public void add(Address address) {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        address.setOwnName(name);
        if (address.getIsDefault()) {
            this.setZero();
        }

        this.addressDao.insertSelective(address);
    }

    public List<Address> selectByOwnName() {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String ownName = principal.getUsername();
        List<Address> addresses = this.addressDao.selectByExample(ownName);
        return addresses;
    }

    public Address selectDefaultByOwnName() {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        String isDef = "1";
        Address address = this.addressDao.selectOneByExample(name, isDef);
        return address;
    }

    public void defaultAddressInfoUpdate(Address address) {
        UserDetails principal = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String name = principal.getUsername();
        address.setOwnName(name);
        if (address.getIsDefault()) {
            this.setZero();
        }

        this.update(address);
    }

    public void update(Address address) {
        this.addressDao.updateByPrimaryKey(address);
    }

    public boolean delete(Integer id) {
        Address address = this.addressDao.selectByPrimaryKey(id);
        if (address.getIsDefault()) {
            return false;
        } else {
            this.addressDao.deleteByPrimaryKey(id);
            return true;
        }
    }

    public void setZero() {
        Address address = this.selectDefaultByOwnName();
        if (null != address) {
            address.setIsDefault(false);
            this.update(address);
        }

    }
}
